package org.huangrui.spark.java.core.rdd.operate.transform;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author hr
 * @Create 2024-10-17 19:30
 */
public class Spark13_Operate_Transform_KV_sortByKey_2 {
    public static void main(String[] args) {
        final SparkConf conf = new SparkConf().setMaster("local[*]").setAppName("spark");
        final JavaSparkContext jsc = new JavaSparkContext(conf);


        final List<Tuple2<String, Integer>> datas =  new ArrayList<>();
        datas.add(new Tuple2<String, Integer>("a", 1));
        datas.add(new Tuple2<String, Integer>("a", 3));
        datas.add(new Tuple2<String, Integer>("a", 4));
        datas.add(new Tuple2<String, Integer>("a", 2));

        final JavaRDD<Tuple2<String, Integer>> rdd = jsc.parallelize(datas);
        final JavaPairRDD<String, Integer> mapRdd = rdd.mapToPair(t -> t);

        mapRdd.map(t -> new Tuple2<>(t._2, t._1))
                .mapToPair(t->t)
                .sortByKey()
                .map(t -> new Tuple2<>(t._2, t._1))
                .collect().forEach(System.out::println);
        // (a, 1) => (1, (a, 1))
        // (a, 3) => (3, (a, 3))
        // (a, 4) => (4, (a, 4))
        // (a, 2) => (2, (a, 2))
        mapRdd.map(t -> new Tuple2<>(t._2, t))
                .mapToPair(t -> t)
                .sortByKey(false, 1)
                .map(t -> t._2)
                .collect().forEach(System.out::println);


        jsc.close();
    }
}
